﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace MillerApp.CommonLib.Utility
{
    /// <summary>
    /// 实体帮助类
    /// </summary>
    public class EntityHelper
    {
        #region 序列化

        /// <summary>
        /// 反序列化实体(UTF-8编码)
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="xml">xml</param>
        /// <returns>T</returns>
        public static T DeserializeEntity<T>(string xml)
        {
            MemoryStream m = new MemoryStream(Encoding.UTF8.GetBytes(xml));
            StreamReader tr = new StreamReader(m, Encoding.UTF8);
            XmlSerializer mySerializer = new XmlSerializer(typeof(T));
            T result = (T)mySerializer.Deserialize(tr);
            tr.Close();
            mySerializer = null;
            return result;
        }

        /// <summary>
        /// 序列化实体成XML字符串(UTF-8编码)
        /// </summary>
        /// <param name="entity">要序列化实体</param>
        /// <returns>XML字符串</returns>
        public static string SerializeEntity(object entity)
        {
            MemoryStream m = new MemoryStream();
            XmlSerializer mySerializer = new XmlSerializer(entity.GetType());
            mySerializer.Serialize(m, entity);
            m.Position = 0;
            byte[] text = m.ToArray();
            m.Flush();
            m.Close();
            mySerializer = null;
            return Encoding.UTF8.GetString(text, 0, text.Length);
        }

        #endregion 
    }
}
